package cc.cix.hq.org.controller;


import cc.cix.hq.common.core.entity.QueryRequest;
import cc.cix.hq.common.core.entity.Tree;
import cc.cix.hq.common.core.entity.constant.PageConstant;
import cc.cix.hq.common.core.entity.org.Dept;
import cc.cix.hq.org.dto.query.QueryDeptReq;
import cc.cix.hq.org.dto.request.DeptReq;
import cc.cix.hq.org.service.IDeptService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cix
 */
@Api(tags = "部门管理")
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/dept")
public class DeptController {

    private final IDeptService deptService;

    @ApiOperation("部门列表")
    @GetMapping
    public Map<String, Object> listDept(QueryRequest request, QueryDeptReq dto) {
        Dept dept = BeanUtil.toBean(dto, Dept.class);

        // 是否过滤出最后一级
        Map<String, Object> map = deptService.listDept(request, dept);
        if (dto.getIsLast() != null && dto.getIsLast()) {
            List<Tree<?>> rows = (List<Tree<?>>) map.get("rows");
            List<Tree<?>> depts = new ArrayList<>();
            getLastDept(depts, rows);

            Map<String, Object> result = new HashMap<>();
            result.put(PageConstant.ROWS, depts);
            result.put(PageConstant.TOTAL, depts.size());
            return result;
        }

        return map;
    }

    @ApiOperation("添加部门")
    @PreAuthorize("hasAuthority('dept:add')")
    @PostMapping
    public void addDept(@Valid @RequestBody DeptReq dto) {
        Dept dept = BeanUtil.toBean(dto, Dept.class);
        deptService.createDept(dept);
    }

    @ApiOperation("删除部门")
    @PreAuthorize("hasAuthority('dept:delete')")
    @DeleteMapping("/{deptIds}")
    public void deleteDept(@PathVariable String deptIds) {
        deptService.deleteDeptByIds(StrUtil.splitTrim(deptIds, StrUtil.COMMA));
    }

    @ApiOperation("更新部门")
    @PreAuthorize("hasAuthority('dept:update')")
    @PutMapping
    public void updateDept(@Valid @RequestBody DeptReq dto) {
        Dept dept = BeanUtil.toBean(dto, Dept.class);
        deptService.updateDept(dept);
    }

    /**
     * 递归获取最后一级部门
     *
     * @param depts 结果列表
     * @param trees 部门树
     */
    private void getLastDept(List<Tree<?>> depts, List<? extends Tree<?>> trees) {
        trees.forEach(i -> {
            if (i.getChildren() != null && !i.getChildren().isEmpty()) {
                getLastDept(depts, i.getChildren());
            } else {
                depts.add(i);
            }
        });
    }

}
